// SingleProcessKeeper.cpp: implementation of the SingleProcessKeeper class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "SingleProcessKeeper.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

SingleProcessKeeper::SingleProcessKeeper(CWinApp * pApp):
	m_pApp(pApp)
{
	m_pMutex = new CMutex(false, pApp->m_pszAppName);
}

SingleProcessKeeper::~SingleProcessKeeper()
{
	delete m_pMutex;
}

bool SingleProcessKeeper::IsMarked() const
{
	BOOL bRet = m_pMutex->Lock(0);
	if (!bRet)
	{
		CWnd * pWnd = CWnd::GetDesktopWindow()->GetWindow(GW_CHILD);
		while (pWnd)
		{
			if (GetProp(pWnd->GetSafeHwnd(), m_pApp->m_pszAppName))
			{
				pWnd->ShowWindow(SW_SHOW);
				CWnd * pLastActiveWnd = pWnd->GetLastActivePopup();
				pLastActiveWnd->SetForegroundWindow();
				break;
			}
			pWnd = pWnd->GetNextWindow();
		}
	}

	return !bRet;
}

void SingleProcessKeeper::Mark()
{
	SetProp(m_pApp->m_pMainWnd->GetSafeHwnd(), m_pApp->m_pszAppName, (HANDLE)1);
}

void SingleProcessKeeper::Unmark()
{
	RemoveProp(m_pApp->m_pMainWnd->GetSafeHwnd(), m_pApp->m_pszAppName);
}